//
//  HealthLog.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/7/6.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import LTScrollView
import MJRefresh
import SwiftyJSON

class HealthLog: HMViewController {
    // MARK: - 变量
    // 私有， 懒加载
    private lazy var titles: [String] = {
        return ["血压", "体重", "体温", "心率", "血糖"]
    }()
    private lazy var ulrIds: [String] = {
        return ["blood-pressure-all", "weight-all", "body-temp-all","heart-rate-all","blood-glucose-all"]
    }()
    
    private lazy var chartUrls: [String] = {
        return ["user/data/blood-pressure/day","user/data/weight/day","user/data/body-temp/day","user/data/heart-rate/day","user/data/blood-glucose/day"]
    }()
    
    private lazy var averageUrls: [String] = {
       return ["blood-pressure","weight","body-temp","heart-rate","blood-glucose"]
    }()
    
    
    /***
     高度、宽度计算
     */
    private lazy var wUniformity: CGFloat = {
       return (self.view.wWidth - 16)/3
    }()
    private lazy var logH: CGFloat = {
       return 120.0
    }()
    private lazy var barH: CGFloat = {
       return CGFloat((navigationController?.navigationBar.wHeight)!)
    }()
    private var statusH: CGFloat {
       return UIApplication.shared.statusBarFrame.height
    }
    
    
    // viewControllers // 每个
    private lazy var viewCs: [UIViewController] = {
        var vcs  = [UIViewController]()
        var i = 0
        for str in titles {
            var contents = ChartContent() // ChartContent tableView 内容
            contents.adjustValue =  120.0 + 16.0 // 调整内容的高度
            contents.cc_healthLog = self
            contents._title = str
            contents.urlId = ulrIds[i]
            contents.chartUrl = chartUrls[i]
            contents.averageUrl = averageUrls[i]
            vcs.append(contents)
    
            i += 1
        }
        return vcs
    }()
    
    //dataJson urlId
    
    private lazy var layout: LTLayout = {
        let layout = LTLayout()
//        layout.bottomLineHeight = 4.0
//        layout.bottomLineCornerRadius = 2.0
        layout.isAverage = true
        layout.sliderWidth = 20
        layout.bottomLineColor = configure.shareConfigure.HMColor1
        layout.titleSelectColor = configure.shareConfigure.HMColor1
        layout.titleViewBgColor = UIColor.white
        /* 更多属性设置请参考 LTLayout 中 public 属性说明 */
        return layout
    }()
    
    private lazy var simpleManager: LTSimpleManager = {
        let Y: CGFloat = 16.0 + logH
        let H: CGFloat = glt_iphoneX ? (view.bounds.height - Y - 34) : view.bounds.height - Y - (16 + 44)
        
        let simpleManager = LTSimpleManager(frame: CGRect(x: 0, y: Y, width: view.bounds.width, height: H), viewControllers: viewCs, titles: titles, currentViewController: self, layout: layout)
  //   simpleManager.backgroundColor = configure.shareConfigure.HMColor1
        /* 设置代理 监听滚动 */
        simpleManager.delegate = self

        /* 设置悬停位置 */
        // simpleManager.hoverY = 64

        /* 点击切换滚动过程动画 */
         simpleManager.isClickScrollAnimation = true

        /* 代码设置滚动到第几个位置 */
        //        simpleManager.scrollToIndex(index: 1)

        /* 动态改变header的高度 */
        //        simpleManager.glt_headerHeight = 180

        return simpleManager
    }()
    
    
    
    
    // MARK: - 常量
    let log = homeIconView()
    let data = homeIconView()
    let report = homeIconView()
    
    let scrollView = UIScrollView()
    let con = HMTableViewController()
    
    // MARK: - 周期
    override func viewDidLoad() {
//        self.isHideNavigationBar = true
        self.tabBarController?.tabBar.isHidden = true
        self.automaticallyAdjustsScrollViewInsets = false
        super.viewDidLoad()
        simpleManagerConfig()
//        UserDefaults.standard.set(true, forKey:"HEALTH_INIT")
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated) //离开
        print("2----------------YTYanK----WillDisappear")  //返回来到了这里
        
//         UserDefaults.standard.set(self.ulrIds[index], forKey: configure.shareConfigure.HEALTH_SELECT_INDEX)
//        UserDefaults.standard.remove
        
    }
    
    // MARK: - 配置view
    override func setupView() {
        self.title = "健康日志"
        view.backgroundColor = UIColor.white
        
        view.addSubview(log)
        view.addSubview(data)
        view.addSubview(report)
        view.addSubview(scrollView)
        view.addSubview(simpleManager)
       
        
        log.topAlign(view: view)
        log.leadingAlign(view: view)
        log.widthConstrain(predicate: "\(wUniformity)")
        log.heightConstrain(predicate: "\(logH)")
        log.setData(imgName: "friends", title: "亲友日志")
        log.addLayer(isAddLayer: (false, false, true, false), color: UIColor.gray, crude: 1, layout: (w: wUniformity, h: logH))
        log.delegate = self
        log.tag = 1010
        
        
        data.topAlign(view: view)
        data.leadingHorizontally(view: log, predicate: "0")
        data.widthConstrain(predicate: "\(wUniformity)")
        data.heightConstrain(predicate: "\(logH)")
        data.setData(imgName: "Entry", title: "数据录入")
        data.addLayer(isAddLayer: (false, false, true, false), color: UIColor.gray, crude: 1, layout: (w: wUniformity, h: logH))
        data.delegate = self
        data.tag = 1011
        
        
        report.topAlign(view: view)
        report.leadingHorizontally(view: data, predicate: "0")
        report.widthConstrain(predicate: "\(wUniformity)")
        report.heightConstrain(predicate: "\(logH)")
        report.setData(imgName: "Physical", title: "体验报告")
//        report.backgroundColor = UIColor.red
        report.delegate = self
        report.tag = 1012
    }
//    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//        // Get the new view controller using segue.destinationViewController.
//        // Pass the selected object to the new view controller.
//        
//            
//        
//      //  if segue.identifier === ""
//    }
    
}

extension HealthLog {
    //MARK: 具体使用请参考以下
    private func simpleManagerConfig() {
        
        //MARK: headerView设置
//        simpleManager.configHeaderView {[weak self] in
//            guard let strongSelf = self else { return nil }
//            let headerView = strongSelf.testLabel()
//            return headerView
//        }Z
        //MARK: pageView点击事件
        simpleManager.didSelectIndexHandle { (index) in
            print("选项点击了 \(index) 😆")
            let isInit =  UserDefaults.standard.string(forKey: self.ulrIds[index])
            
            if isInit == ""  {
                    //self.ulrIds[index]
                            let vc = self.viewCs[index] as! ChartContent
                
                            let d  = Date()
                            let startStr = "\(d.year)-\(d.month)-\(d.day) 00:00:00";
                            let endStr = "\(d.year)-\(d.month)-\(d.day) 23:00:00";
                
                            let startDate = Date.getFromDate(dateString: startStr)
                            let endDate =   Date.getFromDate(dateString:  endStr)
                
                            let startInt = ((startDate?.timeIntervalSince1970)! * 1000)
                            let endInt = ((endDate?.timeIntervalSince1970)! * 1000)
                
                            NetRequestTool.shareInstance.met = .get
                            NetRequestTool.request(url: "user/data/" + self.ulrIds[index], parameters: ["st": startInt, "et": endInt, "page": 0, "perPage": 100], success: { (json) in
                
                                vc.dataJson = json["data"]["list"];
                                vc.chartDataJson =  json["data"]["list"];
                                vc.CCTableView.reloadData()
                            }, fail: { (code, err) in
                                // print("---->>>", code, err);
                            }) {

                            }
        

            }else  {
                UserDefaults.standard.set("", forKey: self.ulrIds[index])
            }
            
            
        }
        
    }
    
    @objc private func tapLabel(_ gesture: UITapGestureRecognizer)  {
        print("tapLabel☄")
    }
}
//extension HealthLog {
//    private func testLabel() -> UILabel {
//        let headerView = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 180))
//        headerView.backgroundColor = UIColor.red
//        headerView.text = "点击响应事件"
//        headerView.textColor = UIColor.white
//        headerView.textAlignment = .center
//        headerView.isUserInteractionEnabled = true
//        headerView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tapLabel(_:))))
//        return headerView
//    }
//}




// homeIconViewDelegate
extension HealthLog: homeIconViewDelegate {
    func viewTapClick(view: UIView) {
        if (view.tag == 1011) {
            let storyBoard = UIStoryboard(name: "Main", bundle: nil)
            let _device : Device = storyBoard.instantiateViewController(withIdentifier: "device") as! Device
            self.pushViewController(_device)
            
        }else if view.tag == 1010 {
              let _friendLog =  FriendLog()
              self.pushViewController(_friendLog)  
        }else {
            // 进入体检报告
//            NetRequestTool.shareInstance.met = .get
//            NetRequestTool.request(url: "user/exam-report/list", parameters: [:], success: { (json) in
                let _pre  = Presentation()
//                _pre.jsonData = json["data"]
                self.pushViewController(_pre)
//            }, fail: { (code, msg) in
//                print("----->>", msg)
//            }) { }

        }
    }
}

// LTSimpleScrollViewDelegate
extension HealthLog: LTSimpleScrollViewDelegate {
    
    //MARK: 滚动代理方法
    func glt_scrollViewDidScroll(_ scrollView: UIScrollView) {
        //        print("offset -> ", scrollView.contentOffset.y)
    }
    
    //MARK: 控制器刷新事件代理方法
    func glt_refreshScrollView(_ scrollView: UIScrollView, _ index: Int) {
        //注意这里循环引用问题。
        scrollView.mj_header = MJRefreshNormalHeader {[weak scrollView] in
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
                print("对应控制器的刷新自己玩吧，这里就不做处理了🙂-----\(index)")
                scrollView?.mj_header.endRefreshing()
            })
        }
    }
}
